<?php

namespace App\Repositories;

use App\Repositories\BaseInterface\Repository;
use App\Repositories\Contracts\AttachmentRepositoryInterface;
use App\Models\Attachment;
use Illuminate\Support\Facades\Storage;
use Illuminate\Support\Facades\Log;
use Intervention\Image\Facades\Image;
use App\Utils\LocalStorePath;

class AttachmentRepository extends Repository implements AttachmentRepositoryInterface
{

  public function model()
  {
    return "App\Models\Attachment";
  }

  public function upload($file)
  {
    $files  = [];
    $result = [];
    if (!$file) {
      return null;
    } elseif ($file instanceof \Illuminate\Http\UploadedFile) {
      array_push($files, $file);
    } elseif (is_array($file)) {
      foreach ($file as $item) {
        if ($item instanceof \Illuminate\Http\UploadedFile) {
          array_push($files, $item);
        }
      }
    }
    foreach ($files as $item) {
      $data        = [];
      $data['md5'] = md5_file($item->getRealPath(), false);
      $record      = $this->findBy('md5', $data['md5']);
      if ($record) {
        $path = str_replace(Storage::disk("public")->url('/'), "", $record->url);
        $fileName = basename($path);
        $path = dirname($path);
        $data['filename'] = $record->filename;
      } else {
        $data['ext_name']  = strtolower($file->getClientOriginalExtension());
        $fileName          = date('Ymd') . '-' . mt_rand(10000000, 99999999) . '.' . $data['ext_name'];
        $path              =  date('Y/m-d');
        $data['filename']  = $file->getClientOriginalName();
        $data['mime_type'] = $file->getClientMimeType();
        $data['size']      = $file->getSize();
        $data['url']       = Storage::disk("public")->url($path . '/' . $fileName);
        $record            = $this->create($data);
      }
      if (!Storage::disk("public")->exists($path . "/" . $fileName)) {
        Storage::putFileAs($path, $item, $fileName);
      }
      if ($record) {
        array_push($result, $record);
      }
    }
    return $result;
  }


  /**

   * @param int $id 附件id
   * @return \App\Utils\LocalStorePath
   */

  public function localFileInfo($id)
  {
    Log::debug("加载文件");

    $attachment = $this->find($id);
    if (!$attachment) {
      return false;
    }

    $result =  new LocalStorePath($attachment->url);
    if (!$result->exists()) {
      // Log::debug("文件没有找到");
      return false;
    }

    return $result;
  }

  /**
   * @param \App\Utils\LocalStorePath $fileInfo
   * @param int $newWidth
   * @param int $newHeight
   * @param int $scale
   * @return string
   */
  public function imageSize($fileInfo, $newWidth = 0, $newHeight = 0, $scale = true)
  {
    if (!$fileInfo) {
      return false;
    }
    if ((!$newWidth || intval($newWidth) < 1) && (!$newHeight || intval($newHeight) < 1)) {
      Log::debug("高度，宽度没有设置");
      $newHeight = 600;
      $newWidth = 800;
    }
    // 高度、宽度没有设置时，自动按比例进行缩放
    $image = Image::make($fileInfo->getRealFilePath());
    $oldWidth = $image->width();
    $oldHeight = $image->height();
    // 处理比例
    if (!$newWidth || $newWidth < 1) {
      $newWidth = intval($newHeight * $oldWidth / $oldHeight);
      Log::debug("宽度没有设置");
      $scale = true;
    }
    if (!$newHeight || $newHeight < 1) {
      Log::debug("高度度没有设置");
      $newHeight = intval($newWidth * $oldHeight / $oldWidth);
      $scale = true;
    }
    if ($scale) {
      Log::debug("计算比例");
      if ($oldWidth / $oldHeight > $newWidth / $newHeight) {
        $newHeight = intval($newWidth * $oldHeight / $oldWidth);
      } else {
        $newWidth = intval($newHeight * $oldWidth / $oldHeight);
      }
    }
    $exName = "{$newWidth}x{$newHeight}";
    //文件不存在时，写入图片
    if (!$fileInfo->existsThumbnailName($exName)) {
      Log::debug("文件重置图片写入");
      $image->resize($newWidth, $newHeight);
      $image->save($fileInfo->getThumbnailRealName($exName));
    }
    $image = null;
    return $fileInfo->getThumbnailUrl($exName);
  }
}
